package com.huiquan.management.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.dao.PageRoleDao;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.management.domain.Page;

@Service
public class PageService extends BaseService {

	@Autowired
	private PageRoleDao pageRoleDao;

	public ModelAndView list() {

		Map<String, Object> param = new HashMap<>();
		param.put("type", "1");
		List<Page> pageList = pageRoleDao.retrieveList(param);

		for (Page page : pageList) {
			param.clear();
			param.put("type", "2");
			param.put("parentId", page.getId()+"");
			List<Page> tabList = pageRoleDao.retrieveList(param);
			page.setPageList(tabList);
			if(tabList != null && tabList.size()>0){
				page.setPageNum(tabList.size()+2);
			}else{
				page.setPageNum(2);
			}
		}

		Map<String, Object> map = new HashMap<>();
		map.put("list", pageList);

		return new ModelAndView("management/index", map);
	}

	private int getPageNum(int i) {
		// TODO Auto-generated method stub
		return 0;
	}

	public ReturnData updateClass(long id, User user, String type, String value) {
		Page param = new Page();
		if(StringUtils.equals(type, "1")){
			param.setTabName(value);;
		}else if(StringUtils.equals(type, "2")){
			param.setTabId(value);;
		}else if(StringUtils.equals(type, "3")){
			param.setRank(Integer.parseInt(value));;
		}else if(StringUtils.equals(type, "4")){
			param.setUrl(value);
		}
		param.setId(id);
		pageRoleDao.update(param);
		
		return ReturnUtil.success();
	}
	public ReturnData deleteClass(long id) {
		Page param = new Page();
		param.setId(id);
		pageRoleDao.delete(param);
		
		return ReturnUtil.success();
	}
	
	public ReturnData deleteClassAll(long id) {
		Map<String, Object> param = new HashMap<>();
		param.put("type", "2");
		param.put("parentId", id);
		List<Page> pageList = pageRoleDao.retrieveList(param);
		for(Page page:pageList){
			pageRoleDao.deleteRelatByTabId(page.getId());
		}
		Page page = new Page();
		//删除大类下页面
		page.setParentId(id);
		pageRoleDao.delete(page);
		//删除大类
		page = new Page();
		page.setId(id);
		pageRoleDao.delete(page);
		return ReturnUtil.success();
	}
	
	
	public ReturnData addClass(long id,String name,String url,String tabId,String rank) {
		Page param = new Page();
		param.setParentId(id);
		param.setRank(Integer.parseInt(rank));
		param.setTabId(tabId);
		param.setTabName(name);
		param.setType(id == 0 ?1:2);
		param.setUrl(StringUtils.isBlank(url)?"":url);
		pageRoleDao.insert(param);
		return ReturnUtil.success();
	}
}
